﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.IO;
using System.Configuration;
using System.Reflection;
using Microsoft.Win32;

namespace BatteryAlarm
{
    public partial class MainForm : Form
    {

        // For Windows Mobile, replace user32.dll with coredll.dll 
        [DllImport("user32.dll")]

        static extern bool SetForegroundWindow(IntPtr hWnd);
        private bool mShowAllowed;
        private bool mCloseAllowed;
        private IntPtr hWnd;
        private bool fullBatteryNotify;
        System.Media.SoundPlayer myPlayer = new System.Media.SoundPlayer();
        private string wavFile;

        public MainForm()
        {
            
            InitializeComponent();
            niTrayIcon.ContextMenuStrip = ctxMenuStrip;
            niTrayIcon.MouseDoubleClick += niTrayIcon_MouseDoubleClick;
            niTrayIcon.BalloonTipClicked += new EventHandler(niTrayIcon_BalloonTipClicked);
            openToolStripMenuItem.Click += openToolStripMenuItem_Click;
            exitToolStripMenuItem.Click += exitToolStripMenuItem_Click;

            SystemEvents.PowerModeChanged += new PowerModeChangedEventHandler(SystemEvents_PowerModeChanged);

            string winDir = Environment.GetEnvironmentVariable("WINDIR");
            fdOpenWavFile.DefaultExt = "*.wav";
            if (Directory.Exists(winDir + @"\media"))
                fdOpenWavFile.InitialDirectory = winDir + @"\media";
            else
                fdOpenWavFile.InitialDirectory = winDir;

            spinRepeat.Value = Properties.Settings.Default.RepeatMinutes;
            spinPercent.Value = Properties.Settings.Default.PowerLevel;
            cbFullBattery.Checked = Properties.Settings.Default.FullBatteryNotify;
            wavFile = Properties.Settings.Default.WAVFile;

            niTrayIcon.ShowBalloonTip(10, "Battery Alarm", "You will be notified when the power level reaches " + spinPercent.Value.ToString() + "%.", ToolTipIcon.Info);

            tbxPlayFile.Text = wavFile;

            timer1.Interval = (Int32)(spinRepeat.Value * 60) * 1000;

            Assembly assembly = Assembly.GetExecutingAssembly();
            this.Text = "Battery Alarm " + assembly.GetName().Version.ToString(4);


            //string path = Path.GetDirectoryName(assembly.GetModules()[0].FullyQualifiedName) + "\\Donate.htm";
            //string path = 
            //webBrowser1.Navigate(path);
            setDonatePage();
           // webBrowser1..Url = new Uri("file://Donate.htm");


        }

        void niTrayIcon_BalloonTipClicked(object sender, EventArgs e)
        {
            stopSound();
        }

        private void setDonatePage()
        {
            using (Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream("BatteryAlarm.Donate.htm"))
            {
                using (StreamReader r = new StreamReader(s))
                {
                    string html = r.ReadToEnd();

                    webBrowser1.Document.Write(html);
                }
            }
           
        }
        
        private void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
        {
            PowerStatus ps = SystemInformation.PowerStatus;

            if (PowerLineStatus.Online != ps.PowerLineStatus)
            {
                if ((ps.BatteryLifePercent * 100) <= (float)spinPercent.Value)
                    timer1.Start();

                // if we aren't plugged in, don't tell me when the battery is full.
                fullBatteryNotify = false;
            }
            else
            {
                timer1.Stop();
                stopSound();
                // if we are plugged in, tell me when the battery is full.
                fullBatteryNotify = cbFullBattery.Checked;
            }

            UpdateUI();
        }

        protected override void SetVisibleCore(bool value)
        {
            // Prevent form from getting visible at startup
            if (!mShowAllowed) value = false;
            base.SetVisibleCore(value);
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            // Hide when user clicks the X
            if (!mCloseAllowed)
            {
                e.Cancel = true;
                Hide();
                mShowAllowed = false;
            }

        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Context menu item "Open"
            mShowAllowed = true;
            Show();
            WindowState = FormWindowState.Normal;
            hWnd = Process.GetCurrentProcess().MainWindowHandle;
            SetForegroundWindow(hWnd);
        }

        private void SaveSettings()
        {
            Properties.Settings.Default.FullBatteryNotify = cbFullBattery.Checked;
            Properties.Settings.Default.PowerLevel = Int32.Parse(spinPercent.Value.ToString());
            Properties.Settings.Default.RepeatMinutes = Int32.Parse(spinRepeat.Value.ToString());
            Properties.Settings.Default.WAVFile = tbxPlayFile.Text;
            Properties.Settings.Default.Save();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Context menu item "Exit"
            try
            {
                mCloseAllowed = true;
                niTrayIcon.Visible = false;
                timer1.Stop();
                timerUIUpdate.Stop();

                SaveSettings();
                //Configuration oConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

                //oConfig.AppSettings.Settings["RepeatMinutes"].Value = spinRepeat.Value.ToString();
                //oConfig.AppSettings.Settings["PowerLevel"].Value = spinPercent.Value.ToString();
                //oConfig.AppSettings.Settings["WAVFile"].Value = tbxPlayFile.Text;
                //oConfig.AppSettings.Settings["FullBatteryNotify"].Value = cbFullBattery.Checked.ToString();

                //oConfig.Save(ConfigurationSaveMode.Minimal);

                //remove event handler
                SystemEvents.PowerModeChanged -= new PowerModeChangedEventHandler(SystemEvents_PowerModeChanged);

                Application.Exit();
            }
            catch (Exception ex)
            {
                //MessageBox.Show("Unable to update your settings.  Make sure you have permissions to write files in the directory: " +
                //                    Application.StartupPath + ".", "Battery Alarm", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        private void niTrayIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            // Also open on double-click
            if (e.Button == MouseButtons.Left)
            {
                if (Visible == false || WindowState == FormWindowState.Minimized)
                {
                    mShowAllowed = true;
                    Show();
                    WindowState = FormWindowState.Normal;
                    hWnd = Process.GetCurrentProcess().MainWindowHandle;
                    SetForegroundWindow(hWnd);
                }

                else
                {
                    Hide();
                    mShowAllowed = false;
                }
            }
        }

        private void Form1_Activated(object sender, EventArgs e)
        {
            UpdateUI();
        }

        private void btnPlay_Click(object sender, EventArgs e)
        {
            myPlayer.SoundLocation = wavFile;
            myPlayer.Play();
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            fdOpenWavFile.ShowDialog();

            wavFile = fdOpenWavFile.FileName;
            tbxPlayFile.Text = wavFile;
        }

        private void spinRepeat_ValueChanged(object sender, EventArgs e)
        {
            timer1.Stop();
            timer1.Interval = (Int32)(spinRepeat.Value * 60) * 1000;
            
            PowerStatus ps = SystemInformation.PowerStatus;
            if (PowerLineStatus.Online != ps.PowerLineStatus)
            {
                if ((ps.BatteryLifePercent * 100) <= (float)spinPercent.Value)
                    timer1.Start();
            }
        }
        

        private void timer1_Tick(object sender, EventArgs e)
        {
            PowerStatus ps = SystemInformation.PowerStatus;

            if (PowerLineStatus.Online == ps.PowerLineStatus)
                return;
            
            playSound();
        }

        private void popupPowerLevel()
        {
            PowerStatus ps = SystemInformation.PowerStatus;

            if (ps.PowerLineStatus == PowerLineStatus.Online)
                niTrayIcon.ShowBalloonTip(10, "Battery Alarm", "Power level is now at 100%.", ToolTipIcon.Info);
            else
                niTrayIcon.ShowBalloonTip(10, "Battery Alarm", "Power level is now at " + (100 * ps.BatteryLifePercent).ToString() + "%." + Environment.NewLine + GetLifeRemaining(ps), ToolTipIcon.Warning);
        }

        private void playSound()
        {
            try
            {
                myPlayer.SoundLocation = wavFile;
                myPlayer.Play();
                
            }
            catch (Exception ex)
            {
                MessageBox.Show("The file selected is not a valid WAV file.  Please select a new file", "Battery Alarm", MessageBoxButtons.OK, MessageBoxIcon.Error);
                timer1.Stop();
            }
        }

        private void spinPercent_ValueChanged(object sender, EventArgs e)
        {
            timer1.Stop();
            niTrayIcon.ShowBalloonTip(10, "Battery Alarm", "You will be notified when the power level reaches " + spinPercent.Value.ToString() + "%.", ToolTipIcon.Info);

            PowerStatus ps = SystemInformation.PowerStatus;

            if (PowerLineStatus.Online != ps.PowerLineStatus)
            {
                if ((ps.BatteryLifePercent * 100) <= (float)spinPercent.Value)
                    timer1.Start();
            }
        }

        private string GetLifeRemaining(PowerStatus ps)
        {
            string txt = "Plugged In, Charging.";

            if (ps.PowerLineStatus != PowerLineStatus.Online)
            {
                if (ps.BatteryLifeRemaining > 0)
                {
                    TimeSpan ts = new TimeSpan(0, 0, ps.BatteryLifeRemaining);
                    txt = ts.Hours.ToString() + " hr " + ts.Minutes.ToString() + " min remaining.";
                }
                else
                    txt = "";
            }
            return txt;
        }

        private void UpdateUI()
        {
            PowerStatus ps = SystemInformation.PowerStatus;
            string lifeLeft = GetLifeRemaining(ps);

            if (!String.IsNullOrEmpty(lifeLeft))
            {
                LblBatteryLifePercent.Text = (ps.BatteryLifePercent * 100) + "%";
                lblstatus.Text = lifeLeft;

            }
            else
            {
                LblBatteryLifePercent.Text = (ps.BatteryLifePercent * 100) + "%";
                lblstatus.Text = "";
            }

            progressBar1.Value = (Int32)(ps.BatteryLifePercent * 100);

        }

        private void timerUIUpdate_Tick(object sender, EventArgs e)
        {
            PowerStatus ps = SystemInformation.PowerStatus;

            UpdateUI();
            if (ps.PowerLineStatus != PowerLineStatus.Online)
            {
                // not plugged in
                if ((ps.BatteryLifePercent * 100) <= (float)spinPercent.Value)
                {
                    if (!timer1.Enabled)
                    {
                        popupPowerLevel();
                        playSound();
                        timer1.Start();
                    }
                }
            }
            else
            {
                //plugged in
                if ((ps.BatteryLifePercent * 100 == 100) && (fullBatteryNotify))
                {
                    // only notify once. don't play sound
                    popupPowerLevel();
                    fullBatteryNotify = false;
                   
                }
            }
        }

        private void stopSound()
        {
            myPlayer.Stop();
        }

        private void cbFullBattery_CheckedChanged(object sender, EventArgs e)
        {
            PowerStatus ps = SystemInformation.PowerStatus;
            if (cbFullBattery.Checked && (ps.BatteryLifePercent * 100 != 100))
                fullBatteryNotify = true;
        }

        private void MainForm_Deactivate(object sender, EventArgs e)
        {
            SaveSettings();
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            stopSound();
        }
       
        private void pictureBox1_Click(object sender, EventArgs e)
        {

        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void MainForm_Load(object sender, EventArgs e)
        {

        }


    }

}
